package com.api.sdk;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.api.apicommon.response.BaseResponse;
import com.api.apicommon.response.ErrorCode;
import com.api.apicommon.response.ResultUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class HttpRequestUtil {


    /**
     * @param params
     */
    public HttpResponse sendGetRequest(String url, HashMap<String, Object> params, HashMap<String, String> headers, int timeout) {
        HttpRequest httpRequest = HttpRequest.get(url)
                .charset(StandardCharsets.UTF_8)
                .timeout(timeout)
                .form(params)
                .contentType("application/json")
                .addHeaders(headers);
        return httpRequest.execute();
    }
    /**
     * @param params
     * @param headers
     * @param body
     * @param contentType
     * @return
     */
    public BaseResponse sendPostRequest(String url, HashMap<String, Object> params, HashMap<String, String> headers, String body, String contentType,int timeout) {
        HttpRequest httpRequest = HttpRequest.post(url)
                .charset(StandardCharsets.UTF_8)
                .timeout(timeout)
                .form(params)
                .contentType("application/json")
                .addHeaders(headers)
                .body(body, contentType);
        BaseResponse response;
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (httpResponse.getStatus() == HttpStatus.HTTP_OK) {
                response = ResultUtils.success(httpResponse.body());
            } else {
                response = ResultUtils.error(httpResponse.getStatus(), httpResponse.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
        }
        return response;
    }

}
